﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;

namespace Enough.Converter
{
    public class BackgroundColorToBWForegroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null)
            {
                value = parameter;
            }
            if (value == null || (value.ToString().Length < 6))
            {
                return new SolidColorBrush(Colors.Black);
            }
            string strValue = value.ToString();
            if (strValue[0] == '#')
            {
                strValue = strValue.Substring(1);
            }
            uint colorValue = uint.Parse(strValue, System.Globalization.NumberStyles.HexNumber);
            uint grayScale = (((colorValue & 0xff0000) >> 16) + ((colorValue & 0x00ff00) >> 8) + (colorValue & 0x0000ff)) / 3;
            if (grayScale <= 127)
            {
                return new SolidColorBrush(Colors.White);
            }
            else
            {
                return new SolidColorBrush(Colors.Black);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
